package com.dq.controller.api.activity;

import com.alibaba.fastjson.JSONObject;
import com.dq.exception.customException.AdminException;
import com.dq.controller.in.ActivityQuery;
import com.dq.controller.in.ActivityRecordQuery;
import com.dq.controller.in.request.ActivityOrderAdd;
import com.dq.vo.Vo;
import com.dq.domain.activity.Activity;
import com.dq.domain.activity.ActivityRecord;
import com.dq.domain.orders.UserOrder;
import com.dq.domain.org.Org;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.service.AllService;
import com.dq.utils.SmallQrCode;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author liuhui
 * @date 2019/9/22 0022 10:03:45
 */
@RestController
@RequestMapping("api/activity")
@Api(description = "活动")
public class ActivityController extends AllService {

    @Value("${express_time}")
    protected Long expressTime;

    @ApiOperation("活动列表")
    @GetMapping("/query/list")
    public Vo query(){
        List<Activity> activities = activityRepository.findByActivityStatusAndDeletedFalse(Activity.ActivityStatus.on);
        List<Activity.ActivityImgVo> activityImgVoList = new ArrayList<>();
        activities.forEach(activity -> {
            activityImgVoList.add(activity.toActivityImgVo());
        });
        return new Vo(activityImgVoList);
    }

    @ApiOperation("活动列表")
    @PostMapping("/list")
    public Vo list(@RequestBody ActivityQuery activityQuery) throws AdminException{
        return activityService.list(activityQuery);
    }

    @ApiOperation("活动参与记录")
    @PostMapping("activityRecordList")
    public Vo list(@RequestBody ActivityRecordQuery activityRecordQuery) throws AdminException{
        if(null==activityRecordQuery.getPage() || null==activityRecordQuery.getSize()){
            throw new AdminException("缺少必要的请求参数");
        }
        List<ActivityRecord> records = activityRecordService.findByWhere(activityRecordQuery);
        Long total = activityRecordService.countByWhere(activityRecordQuery);
        List<ActivityRecord.UserActivityRecordVo> list = new ArrayList<>();
        records.forEach(record ->{
            list.add(record.recordList());
        });
        PageInfo pageInfo = new PageInfo(list);
        pageInfo.setTotal(total);
        return new Vo(pageInfo);
    }

    @ApiOperation("活动详情")
    @GetMapping("/getActivityDetails/{activityId}")
    public Vo getActivityDetails(@PathVariable @ApiParam Long activityId) throws AdminException{
        Activity activity = dao.get(Activity.class,activityId);
        if(activity == null){
            throw new AdminException("此活动不存在");
        }
        SysUser user = shiroService.getUser();
        if(user == null){
            throw new AdminException("请先登录");
        }
        ActivityRecord activityRecords = activityRecordRepository.findBySysUserAndActivityAndDeletedFalse(user, activity);
        boolean flag = false;
        if(activityRecords ==null ){
            flag = true;
        }
        HashMap<String,Object> map = new HashMap<>();
        map.put("activityInfo",activity.toActivityDetails());
        map.put("flag",flag);
        return new Vo(map);
    }

    @ApiOperation("参与活动(免费)")
    @PostMapping("joinActivity/{activityId}")
    public Vo joinActivity(@PathVariable @ApiParam("活动id") Long activityId) throws AdminException{
        SysUser user = shiroService.getUser();
        Activity activity = dao.get(Activity.class,activityId);
        if(activity == null){
            throw new AdminException("活动已不存在");
        }
        ActivityRecord activityRecords = activityRecordRepository.findBySysUserAndActivityAndDeletedFalse(user, activity);
        if(activityRecords != null){
            throw new AdminException("已经报过名了");
        }
        ActivityRecord activityRecord = new ActivityRecord();
        activityRecord.setActivity(activity);
        activityRecord.setSysUser(user);
        activityRecord.setSysDept((Org) user.getSection());
        activityRecord.setCreateTime(System.currentTimeMillis());
        activityRecordRepository.save(activityRecord);
        return new Vo(HttpStatus.OK);
    }

    @ApiOperation("参与活动(付费)")
    @PostMapping("joinChargeActivity")
    @Transactional
    public Vo joinChargeActivity(@RequestBody ActivityOrderAdd activityOrderAdd) throws AdminException{
        SysUser user = shiroService.getUser();
        Activity activity = dao.get(Activity.class,activityOrderAdd.getActivityId());
        if(activity == null){
            throw new AdminException("活动已不存在");
        }
        ActivityRecord activityRecords = activityRecordRepository.findBySysUserAndActivityAndDeletedFalse(user, activity);
        if(activityRecords != null){
            throw new AdminException("已经报过名了");
        }
        UserOrder userOrder = ordersService.submitActivityOrder(activity,user,expressTime,activityOrderAdd);
        ActivityRecord activityRecord = new ActivityRecord();
        activityRecord.setActivity(activity);
        activityRecord.setSysUser(user);
        activityRecord.setSysDept((Org) user.getSection());
        dao.save(activityRecord);
        return new Vo("200","ok",userOrder.getOrdersNo());
    }

    @ApiOperation("生成小程序活动二维码,返回base64String")
    @GetMapping("/generate/small/{id}/{phone}/{width}")
    public Object generateActivitySmall(@PathVariable Long id,@PathVariable String phone,@PathVariable String width){
        String accessToken = SmallQrCode.getAccessToken();
        String base64Code = SmallQrCode.getWXQrcode(accessToken,"pages/mine/activity/detail",""+id+"&"+phone,Integer.parseInt(width));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","200");
        jsonObject.put("imgUrl",base64Code);
        return jsonObject;
    }

}
